from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical

# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 对训练集中的图片进行预处理
n_train = X_train.shape[0]
X_train = X_train.reshape(n_train, 28, 28, 1)
X_train = X_train / 255
y_train = to_categorical(y_train)

# 对测试集中的数据进行预处理
n_test = X_test.shape[0]
X_test = X_test.reshape(n_test, 28, 28, 1)
X_test = X_test / 255
y_test = to_categorical(y_test)

from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import RMSprop

# 构建全连接神经网络
model = Sequential()
# 第一个卷积层与第一个池化层
model.add(Conv2D(filters=32,
                 kernel_size=(3, 3),
                 activation='relu',
                 input_shape=(28, 28, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
# 第二个卷积层与第二个池化层
model.add(Conv2D(filters=64,
                 kernel_size=(3, 3),
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# 扁平化
model.add(Flatten())
# 全连接层
model.add(Dense(64, activation='relu'))
# 输出层
model.add(Dense(10, activation='softmax'))
model.summary()

model.compile(optimizer=RMSprop(),
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(X_train,
          y_train,
          epochs=10,
          validation_split=0.1,
          verbose=2,
          batch_size=64)
